package com.hanserwei.han_picture.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 异步任务配置
 * 
 * @author hanserwei
 */
@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * AI处理任务线程池
     */
    @Bean("aiProcessExecutor")
    public Executor aiProcessExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：同时处理AI请求的数量（考虑到AI接口的限制）
        executor.setCorePoolSize(2);
        // 最大线程数
        executor.setMaxPoolSize(3);
        // 队列容量：等待处理的任务数量
        executor.setQueueCapacity(50);
        // 线程名前缀
        executor.setThreadNamePrefix("AI-Process-");
        // 拒绝策略：调用者运行
        executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
